<?php
/**
 *      [Haidao] (C)2013-2099 Dmibox Science and technology co., LTD.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      http://www.haidao.la
 *      tel:400-600-2042
 */
class member_favorite_service extends service {

    protected $sqlmap = array();

    public function __construct() {
        $this->table = model('member/member_favorite', 'table');
    }

    public function lists($sqlmap = array(), $limit = 20, $page = 1) {
        $this->sqlmap = array_merge($this->sqlmap, $sqlmap);
        $DB = $this->table->where($this->sqlmap);
        $lists = &$DB->page($page)->limit($limit)->select();
        foreach ($lists as $key => $value) {
            $sku = model('goods/goods_sku', 'service')->goods_detail($value['sku_id']);
            if($sku === false) continue;
            $lists[$key]['_sku'] = $sku;
        }
        $count = &$DB->count();
        return array('count' => $count, 'lists' => $lists);
    }

    public function set_mid($mid) {
        if((int) $mid > 0) {
            $this->sqlmap['mid'] = $mid;
        }
        return $this;
    }

    /* 加入收藏夹 */
    public function add($sku_id, $sku_price = 0) {
        $_sku_info = model('goods/goods_sku', 'service')->goods_detail($sku_id);
        if($_sku_info === false) {
            $this->error = model('goods/goods_sku', 'service')->error;
            return false;
        }
        $this->sqlmap['sku_id'] = $sku_id;
        $this->sqlmap['sku_price'] = $_sku_info['shop_price'];
        if($this->is_exists($sku_id) === true) {
            $this->error = '请勿重复收藏';
            return false;
        }
        $result = $this->table->update($this->sqlmap);
        if(!$result) {
            $this->error = $this->table->getError();
            return false;
        }
        return true;
    }

    public function is_exists($sku_id) {
        $_sqlmap = array();
        $_sqlmap['mid'] = $this->sqlmap['mid'];
        $_sqlmap['sku_id'] = $sku_id;
        return ($this->table->where($_sqlmap)->count() > 0) ? true : false;
    }

    /* 删除收藏夹 */
    public function delete($sku_id = array()) {
        $this->sqlmap['sku_id'] = array("IN", $sku_id);
        $result = $this->table->where($this->sqlmap)->delete();
        if($result === false) {
            $this->error = $this->table->getError();
            return false;
        }
        return true;
    }
}